package lumis.upgrade.custom.build_5_5_0_100115_0;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.dao.DaoFactory;
import lumis.portal.dao.jdbc.ITransactionJdbc;
import lumis.upgrade.IStepHandler;
import lumis.upgrade.IUpgradeDao;
import lumis.util.DatabaseType;
import lumis.util.ITransaction;
import lumis.util.XmlUtil;

import org.w3c.dom.Node;

/**
 * Class responsible for trying to add a new column in lum_Blog. If it already
 * exists (we assume it exists when the select doesn't generates an
 * {@link SQLException} we will not try to add it again.
 * 
 * @version $Revision: 11804 $ $Date: 2010-07-29 10:06:21 -0300 (Thu, 29 Jul 2010) $
 * @since 5.6.0
 */
public class BlogAddPostsPerPage implements IStepHandler
{
	public Node executeStep(SessionConfig sessionConfig, Node stepNode, ITransaction transaction) throws PortalException
	{
		Connection connection = ((ITransactionJdbc) transaction).getConnection();
		try
		{
			PreparedStatement statement = connection.prepareStatement("select postsperpage from lum_Blog");
			try
			{
				statement.setMaxRows(1);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					resultSet.getInt("postsperpage");
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (SQLException e)
		{
			// We will assume this error occurred because column postsperpage
			// doesn't exist yet...
			try
			{
				DatabaseType databaseType = DatabaseType.getDatabaseType(connection);
				String sql;
				switch (databaseType)
				{
					case SQL_SERVER:
						sql = "ALTER TABLE lum_Blog ADD postsperpage INT CONSTRAINT LUM_DF_BLOG_PST_PAG DEFAULT 10 NOT NULL";
						break;
					default:
						sql = "ALTER TABLE lum_Blog ADD postsperpage INT DEFAULT 10 NOT NULL";
				}
				IUpgradeDao upgradeDao = DaoFactory.getUpgradeDao();
				upgradeDao.runSql(sql, transaction);
				upgradeDao.runSql("UPDATE lum_Blog SET postsperpage=50", transaction);
			}
			catch (Exception e1)
			{
				throw new UnexpectedException(e1);
			}
		}

		String stepResult = "<result><success></success></result>";
		Node resultNode = XmlUtil.getDocument(stepResult);
		return resultNode;
	}
}
